package com.fingard.dsp.bank.directbank.bob01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 北京银行历史明细
 * 
 * @author Cruise
 * @date 2019/6/13
 */
public class BOB01Transaction extends BOB01Base implements ITransaction {
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		retAts.writeStart();
		
		String tmpRespCode = "";
		String tmpRespInfo = "";
		
		try {
			String opName = "";
			if ("7515".equals(reqHeader.transType)) {
				opName = this.getBankConfig().getValueAsString("opName7515");
				if (StringHelper.isNullOrEmpty(opName)) {
					opName = "CebankQryCurDetailAddRemOp";
				}
			} else {
				opName = this.getBankConfig().getValueAsString("opName7516");
				if (StringHelper.isNullOrEmpty(opName)) {
					opName = "CebankHisDetailOp";
				}
			}
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());

			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());

			int tmpIntDateFrom = 0;
			int tmpIntDateTo = 0;
			// 按自然月循环查询
			while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
				Calendar tmpClndrStepTo = Calendar.getInstance();
				tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
				// 判断是否跨月
				if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
					// 跨月则设置为月末
					tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
				} else {
					tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
				}

				int tmpBegnum = -2;
				int tmpTotalRdNum = -1;

				while (tmpBegnum <= tmpTotalRdNum && tmpRespCode.length() == 0) {
					if (tmpBegnum < 0) {
						tmpBegnum = 1;
					}
					int tmpPageRdNum = 0;

					XmlTextWriter xmlWriter = new XmlTextWriter();
					writeCommonHeader(xmlWriter);

					xmlWriter.writeStartElement("opReq");
					xmlWriter.writeElementString("opName", opName);
					xmlWriter.writeElementString("serialNo", getQryTransID());
					xmlWriter.writeElementString("reqTime", Format.Date8Format.format(new Date()));
					xmlWriter.writeStartElement("ReqParam");

					xmlWriter.writeElementString("accountNo", p_req7516.actNum);
					if ("7515".equals(reqHeader.transType)) {
						xmlWriter.writeElementClosed("dOcFlag");
					} else {
						xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
						xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
					}

					xmlWriter.writeElementString("minAmount", "0");
					xmlWriter.writeElementString("maxAmount", "9999999999999999");
					if ("7516".equals(reqHeader.transType)) {
						xmlWriter.writeElementClosed("checkNum");
					}
					xmlWriter.writeEndElement();
					xmlWriter.writeEndElement();
					xmlWriter.writeEndDocument();

					String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);

					XmlTextReader tmpBkReader;

					if (tmpStrRet[0].length() == 0) {
						StringBuilder tmpSbMsg = new StringBuilder();
						tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
						if (tmpBkReader != null) {
							String tmpRetCode = tmpBkReader.getFirstText("/BCCBEBankData/opRep/retCode");
							String tmpRetInfo = tmpBkReader.getFirstText("/BCCBEBankData/opRep/errMsg");
							if ("0".equals(tmpRetCode)) {
								while (tmpBkReader.read("/BCCBEBankData/opRep/opResultSet/opResult")) {
									RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
									XElement tmpRetNode = tmpBkReader.readedXElement;

									// #start "MESSAGE 摘要"
									String tmpBK_MESSAGE = tmpRetNode.getSingleTextNotNull("summary").trim();
									tmpRetDetail.comment = tmpBK_MESSAGE;
									tmpRetDetail.abstr = pickupAbstr(tmpBK_MESSAGE);
									// #end

									tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("otherSideBank").trim();
									tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("userRem").trim();

									// #start "发生额、余额、借贷标志: 借，贷"
									String tmpAMT = tmpRetNode.getSingleText("amount").replace(",", "");
									String tmpFLAG1 = tmpRetNode.getSingleText("dOcFlag");
									if ("借".equals(tmpFLAG1)) {
										if (tmpAMT.indexOf('-') < 0) {// 借正，正常业务
											tmpRetDetail.tranAmt = tmpAMT;
											tmpRetDetail.cdFlag = "1";
										} else {// 借负，银行退票,表示收入
											tmpRetDetail.tranAmt = tmpAMT.replace("-", "");
											tmpRetDetail.cdFlag = "2";// 借贷表示置为贷，表示收入
										}
									} else {
										if (tmpAMT.indexOf('-') < 0) {// 贷正，正常业务
											tmpRetDetail.tranAmt = tmpAMT;
											tmpRetDetail.cdFlag = "2";
										} else {// 贷负，目前应该没有这种业务，按照正常的程序逻辑做一下处理
											tmpRetDetail.tranAmt = tmpAMT.replace("-", "");
											tmpRetDetail.cdFlag = "1";// 借贷表示置为借，表示支出
										}
									}
									if (!StringHelper.isNullOrEmpty(tmpRetNode.getSingleText("balance"))) {
										tmpRetDetail.accBal = tmpRetNode.getSingleText("balance").replace(",", ""); // 交易后余额
									}
									// #end

									String tmpStrTRANTIME = tmpRetNode.getSingleText("transTime");
									String tmpStrTRANDATE = tmpRetNode.getSingleText("payDate");
									if ("7515".equals(reqHeader.transType)) {
										tmpStrTRANDATE = Format.Date8Format.format(new Date());
									}

									Date tmpTRANDATETIME;
									if (tmpStrTRANTIME != null && tmpStrTRANTIME.length() == 6) {
										tmpTRANDATETIME = Format.DateTime14Format.parse(tmpStrTRANDATE + tmpStrTRANTIME);// "yyyyMMddHHmmss",

									} else {
										tmpTRANDATETIME = Format.Date8Format.parse(tmpStrTRANDATE);
									}

									Date tmpTRANDATE = Format.Date8Format.parse(tmpStrTRANDATE);
									tmpRetDetail.tranDate = Format.Date10Format.format(tmpTRANDATE);
									tmpRetDetail.tranTime = Format.DateTimeFormat.format(tmpTRANDATETIME);
									tmpRetDetail.valueDate = Format.Date10Format.format(tmpTRANDATE);
									tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("otherAcct").trim();
									tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("otherAcctName").trim();
									// <TRAN_FLOW>交易流水号</TRAN_FLOW>
									tmpRetDetail.payCode = tmpRetNode.getSingleTextNotNull("TRAN_FLOW").trim();
									// <BFLOW>企业支付流水号</BFLOW>
									tmpRetDetail.askNumber = tmpRetNode.getSingleTextNotNull("checkNum").trim();
									tmpRetDetail.reqBatchNO = tmpRetNode.getSingleTextNotNull("checkNum").trim();
									tmpRetDetail.originator = tmpRetNode.getSingleText("checkNum");
									tmpRetDetail.seqId = tmpRetNode.getSingleText("dateNetSerial");
									tmpRetDetail.urid = tmpRetNode.getSingleText("dateNetSerial");
									tmpRetDetail.receiptNo = StringHelper.getFirstNotEmptyTrim(tmpRetNode.getSingleText("dateNetSerial"),tmpRetNode.getSingleText("checkNum"));
									tmpRetDetail.busRef = StringHelper.getFirstNotEmptyTrim(tmpRetNode.getSingleText("checkNum"),tmpRetNode.getSingleText("dateNetSerial"));
									nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
									retAts.writeRetDetail(tmpRetDetail);
								}
							} else if ("F5J09".equals(tmpRetCode)) {
								tmpRespCode = "";
								tmpRespInfo = tmpRetInfo;
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = tmpRetInfo;
								break;
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = tmpSbMsg.toString();
							break;
						}
					} else {
						tmpRespCode = "-1";
						tmpRespInfo = tmpStrRet[1];
						break;
					}
					if (tmpPageRdNum == 0) {
						break;
					}
					tmpBegnum = tmpBegnum + tmpPageRdNum;
				}
				tmpCalendarFrom = tmpClndrStepTo;
				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
				tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		if ("-1".equals(tmpRespCode)) {
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();// 写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		} else if (retAts.getWrittenRdCount() == 0) {
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		
		retAts.writeEnd();
		return retAts;
	}

	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		String tmpStrToday = Format.Date8Format.format(new Date());
		tmpReq7516.dateFrom = tmpStrToday;
		tmpReq7516.dateTo = tmpStrToday;
		return d_7516_HisTrans(tmpReq7516);
	}
}